package atm;

import work.work60.SuperArray;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * 转账界面
 */
public class TransferPanel extends JPanel implements ActionListener {
    private ATMFrame atmFrame;
    private ImageIcon saveImg = new ImageIcon("images/buttonSure.jpg");
    private Font font = new Font("黑体", Font.BOLD, 30);
    private JLabel saveLabel1 = new JLabel("请输入转账金额：");
    private JLabel saveLabel = new JLabel("请输入转账账号：");
    private JTextField accountField = new JTextField();
    private JTextField accountField1 = new JTextField();
    private JButton saveButton = new JButton(saveImg);

    public TransferPanel(ATMFrame atmFrame) {
        this.atmFrame = atmFrame;
        this.setLayout(null);
        saveLabel.setBounds(200, 200, 300, 50);
        saveLabel.setFont(font);
        accountField.setBounds(500, 200, 200, 50);
        accountField.setFont(font);

        saveLabel1.setBounds(200, 300, 300, 50);
        saveLabel1.setFont(font);
        accountField1.setBounds(500, 300, 200, 50);
        accountField1.setFont(font);

        saveButton.setBounds(200, 400, 140, 50);
        saveButton.addActionListener(this);
        this.add(saveLabel);
        this.add(saveLabel1);
        this.add(accountField);
        this.add(accountField1);
        this.add(saveButton);
        this.setOpaque(false);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        User user = atmFrame.getLoginUser();
        if (e.getSource() == saveButton) {
            try {
                Double.parseDouble(accountField1.getText());
            } catch (NumberFormatException e1) {
                JOptionPane.showMessageDialog(null, "必须输入数字");
                return;
            }
            if (Double.parseDouble(accountField1.getText()) > user.getBlance()){
                JOptionPane.showMessageDialog(null,"余额不足");
                return;
            }
            if (saveLabel.getText().equals(user.getAccount())){
                JOptionPane.showMessageDialog(null,"不能转给自己");
                return;
            }
            SuperArray users = atmFrame.getUsers();
            for(int i = 0;i < users.size();i++){
                User otherUser = (User) users.get(i);
                if(otherUser.getAccount().equals(saveLabel.getText())){
                    user.setBlance(user.getBlance() - Double.parseDouble(saveLabel1.getText()));
                    otherUser.setBlance(otherUser.getBlance() + Double.parseDouble(saveLabel1.getText()));
                    JOptionPane.showMessageDialog(this,"转账成功");
                    atmFrame.switchPanel("menu");
                    return;
                }
            }
            JOptionPane.showMessageDialog(this,"输入账号不正确！");
        }
    }
}
